package com.breeze.blockchain.socket.config;

import cn.hutool.core.util.StrUtil;
import com.breeze.components.redis.cluster.id.SnowIdUtil;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;
import lombok.NonNull;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

/**
 * @author breeze
 */
@Component
public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor {

  @Override
  public boolean beforeHandshake(
      @NonNull ServerHttpRequest request,
      @NonNull ServerHttpResponse response,
      @NonNull WebSocketHandler wsHandler,
      @NonNull Map<String, Object> attributes)
      throws Exception {
    HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
    String path = servletRequest.getRequestURI();
    // 非ws路径拦截
    if (StrUtil.isEmpty(path) || !path.startsWith(WebSocketConfig.SOCKET_PATH)) {
      return false;
    }
    // 未登录给个唯一id
    attributes.put(
        WebSocketConfig.SESSION_ID, String.valueOf(SnowIdUtil.getCommonSnowId().nextId()));
    return super.beforeHandshake(request, response, wsHandler, attributes);
  }

  @Override
  public void afterHandshake(
      @NonNull ServerHttpRequest request,
      @NonNull ServerHttpResponse response,
      @NonNull WebSocketHandler wsHandler,
      Exception ex) {
    super.afterHandshake(request, response, wsHandler, ex);
  }
}
